<template>
  <div class="home-wrap h-full relative">
    <!--    <el-alert-->
    <!--      v-if="alertTitle"-->
    <!--      :title="alertTitle"-->
    <!--      type="error"-->
    <!--      show-icon-->
    <!--      :closable="false"-->
    <!--      class="cursor-pointer"-->
    <!--      @click="toNotice"-->
    <!--    />-->
    <!--    !!alertTitle
              ? 'top-[56px] h-[calc(100%_-_72px)]'
              : ' top-[16px] h-[calc(100%_-_32px)]'-->
    <div
      :class="[
        'absolute left-[16px] w-[360px] z-10 flex flex-col gap-[--autata-space-px] overflow-hidden',
        'top-[16px] h-[calc(100%_-_32px)]'
      ]"
    >
      <vxe-card title="" class="w-full" :border="false" :padding="false">
        <div class="flex items-center px-[20px] py-[20px]">
          <div class="w-[58px] h-[58px]">
            <img :src="offOnList[1].image" alt="" />
          </div>
          <div>
            <div class="pl-[24px]">
              <div class="text-[--autata-font-gray-color] text-[16px]">
                {{ t(offOnList[1].title) }}
              </div>
              <div class="num-text">
                <span>{{ offOnList[1].num }}</span>
                <span v-if="offOnList[1].allNum" class="num-all"
                  >/{{ offOnList[1].allNum }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </vxe-card>

      <vxe-card title="" class="w-full" :border="false">
        <AuForm ref="formRef" :formList="formList" :hiddenBtn="true" />
      </vxe-card>

      <vxe-card title="" class="flex-grow" :border="false" :padding="false">
        <div
          class="h-[54px] border-b border-b-[--autata-line-color] pl-[20px] flex items-center"
        >
          <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
          <div class="ml-[8px]">{{ t("welcome.store_distribution") }}</div>
        </div>

        <div ref="cityBarChartRef" class="w-full h-[calc(100%_-_54px)]" />
      </vxe-card>
    </div>
    <baidu-map
      class="bm-view"
      :center="bMapState.center"
      :zoom="bMapState.zoom"
      :mapStyle="bMapState.mapStyle"
      @ready="initMap"
    >
      <CircleMarker
        :pointList="bMapState.pointList"
        @overlayClick="overlayClick"
      />
    </baidu-map>
  </div>
</template>

<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import AuEllipsisTooltip from "@/components/AuEllipsisTooltip/index.vue";
import { storeGroupSelect } from "@/utils/formSelect";
import {
  computed,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  watch
} from "vue";
import TeaImg from "@/assets/dashboard/tea.png";
import OnImg from "@/assets/dashboard/on.png";
import OffImg from "@/assets/dashboard/off.png";
import EmptySvg from "@/assets/svg/empty.svg?component";
import { isArray, storageLocal, useDark, useECharts } from "@pureadmin/utils";
import { deviceCountCharts, formulaHomeAmount, getGeoCode } from "@/api/home";
import {
  COLOR_LIST,
  LINE_COLOR,
  TEXT_COLOR,
  THEME_COLOR
} from "@/utils/constants";
import { initOffDev } from "@/layout/components/lay-navbar/notice";
import { BaiduMap } from "vue-baidu-map-3x";
import { getStoreList } from "@/api/teaInfuser/store";
import customMapJson from "./custom_map_config.json";
import CircleMarker from "@/views/welcome/components/CircleMarker.vue";
import { useRouter } from "vue-router";
import { postGetList } from "@/api/teaInfuser/account";
import { userKey } from "@/utils/auth";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();

defineOptions({
  name: "Welcome"
});

interface PointProp {
  lat: number;
  lng: number;
}

const { isDark } = useDark();
const router = useRouter();
const theme = computed(() => (isDark.value ? "dark" : "light"));
const formList = ref([
  () =>
    storeGroupSelect(
      "group_idlist",
      {
        onChange: submit,
        span: 24,
        label: "welcome.group",
        showAllLevels: false
      },
      true
    )
]);
const { proxy } = getCurrentInstance();

const alertTitle = ref("");

const formRef = ref();
const teaPieChartRef = ref();
const cityBarChartRef = ref();

const offOnList = ref([
  {
    image: TeaImg,
    title: "welcome.today_tea_volume",
    num: 0
  },
  {
    image: OnImg,
    title: "welcome.online_stores",
    allNum: 0,
    num: 0
  },
  {
    image: OffImg,
    title: "welcome.offline_stores",
    allNum: 0,
    num: 0
  }
]);

console.log(customMapJson);
const bMapState = reactive({
  zoom: 5.4,
  center: {
    lng: 108.86607,
    lat: 37.04376
  },
  mapStyle: {
    styleJson: customMapJson
  },
  pointList: [],
  bMap: null,
  map: null
});

const { setOptions: setPieOptions } = useECharts(teaPieChartRef, {
  theme
});
const { setOptions: setCityBarOptions } = useECharts(cityBarChartRef, {
  theme
});
const makeTeaList = ref([]);

const getSearchData = () => {
  const date = new Date();
  const time =
    date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

  const param = formRef.value.getFormData();
  const groupList = param.group_idlist?.map((item: number) => ({
    group_id: item
  }));
  const group_idlist = JSON.stringify(groupList);
  return {
    create_start_time: time + " 00:00:00",
    create_end_time: time + " 23:59:59",
    start_page: 0,
    size: 0,
    group_idlist
  };
};

const initTodayMake = async () => {
  const param = {
    ...getSearchData(),
    groupname: "status"
  };
  const res = await formulaHomeAmount(param);
  for (const item of res.data) {
    if (item.status == 1) {
      offOnList.value[0].num = item.num;
    }
  }
};

const initPieChart = async () => {
  const param = {
    ...getSearchData(),
    groupname: "formula_subid",
    sort: "num_desc",
    status: 1
  };

  let data = [];
  try {
    const res = await formulaHomeAmount(param);
    if (isArray(res.data)) {
      data = res.data.map((v, i) => {
        return {
          name: v.formula_name,
          value: v.num,
          itemStyle: {
            color: COLOR_LIST[i]
          }
        };
      });
    }
  } catch (e) {
    // data = [];
  }
  makeTeaList.value = data;

  setPieOptions({
    tooltip: {
      trigger: "item"
    },
    grid: {
      top: 30,
      left: 0,
      right: 0,
      bottom: 0
    },
    color: COLOR_LIST,
    series: [
      {
        name: t("welcome.device_distribution"),
        type: "pie",
        radius: ["55%", "80%"],
        data,
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center"
        },
        emphasis: {},
        labelLine: {
          show: false
        }
      }
    ]
  });
};

const initCityBarChart = async () => {
  const { group_idlist } = getSearchData();
  const param = {
    select_type: "deviceregion_activation",
    start_page: 0,
    size: 0,
    group_idlist
  };
  let xAxis = [],
    yAxis = [];
  try {
    const res = await getStoreList(param);
    if (isArray(res.data)) {
      // yAxis = res.data.map(v => v.device_num);
      // xAxis = res.data.map(v => v.province);
      let pointData = new Map();
      res.data.forEach(item => {
        const pointKey = item.province + "_" + item.city;
        if (pointData.has(pointKey)) {
          pointData.set(pointKey, pointData.get(pointKey) + 1);
        } else {
          pointData.set(pointKey, 1);
        }
      });
      const entries = Array.from(pointData.entries()).sort(
        (a, b) => a[1] - b[1]
      );
      console.log(entries);
      for (const [key, value] of entries) {
        const [province, city] = key.split("_");
        xAxis.push(city);
        yAxis.push(value);
      }
    }
  } catch (e) {}
  setCityBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      show: false
    },
    grid: {
      left: "3%",
      right: "14%",
      bottom: "5%",
      top: "4%",
      containLabel: true
    },
    dataZoom: [
      {
        type: "inside",
        yAxisIndex: 0,
        realtime: true, //实时更新
        width: 20,
        right: 10,
        start: (function () {
          // 如果数据少于5条，不需要滚动条
          const dataLength = yAxis.length;
          if (dataLength <= 10) {
            return 0; // 显示全部
          } else {
            // 固定显示5条数据
            return 100 - Math.round((10 / dataLength) * 100);
          }
        })(),
        end: 100,
        zoomOnMouseWheel: false, // 启用鼠标滚轮缩放
        moveOnMouseWheel: true // 启用鼠标滚轮平移
      }
      // {
      //   type: "inside",
      //   yAxisIndex: 0,
      //   start: 0,
      //   end: 100,
      //   zoomOnMouseWheel: false, // 启用鼠标滚轮缩放
      //   moveOnMouseWheel: true // 启用鼠标滚轮平移
      //   // preventDefaultMouseWheel: true // 阻止浏览器默认滚动行为
      // }
    ],
    xAxis: {
      type: "value",
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        // showMinLabel: true,
        // interval: 0,
        color: TEXT_COLOR,
        formatter: function (value) {
          if (value.length > 3) {
            return value.substring(0, 3) + "...";
          }
          return value;
        },
        margin: 16
      },
      data: xAxis
    },
    series: [
      {
        name: t("welcome.total"),
        type: "bar",
        barWidth: "10px", // Control bar width
        // barMaxWidth: "10px", // Control bar width
        // barGap: "10%", // Gap between bars if you have multiple series
        itemStyle: {
          color: new proxy.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: "#7BB3FF" },
            { offset: 1, color: THEME_COLOR }
          ])
        },
        label: {
          show: true,
          position: "right"
          // valueAnimation: true,
          // fontWeight: "bold",
          // fontFamily: "DINAlternateBold"
        },
        data: yAxis
      }
    ]
  });
};

const initAlarmDev = async () => {
  const userInfo = storageLocal().getItem(userKey) as any;
  const isFac =
    userInfo.type == 0 ||
    ((userInfo.type == 1 || userInfo.type == 2) &&
      (userInfo.account_svip_status == true ||
        userInfo.account_super_status == true));
  // 不是厂家账号或商家或门店的超级会员账号;
  if (!isFac) {
    const postKey = "powder";
    const postKeyList = storageLocal().getItem(postKey) as any;
    let powerList = postKeyList;
    if (!postKeyList) {
      const post = userInfo.post;
      const postRes = await postGetList({ start_page: 1, size: 1, id: post });
      if (postRes.data.length > 0) {
        powerList = postRes.data[0]?.power_list;
      }
    }
    const parseList = JSON.parse(powerList);
    if (!parseList.includes("StatusNotice")) {
      return;
    }
  }

  initOffDev().then(res => {
    let alarmStr = "";
    if (res.offNum > 0) {
      alarmStr = t("welcome.store_offline_count", { count: res.offNum });
    }
    if (res.deviceNum > 0 && res.offNum > 0) {
      alarmStr += `, `;
    }
    if (res.deviceNum > 0) {
      alarmStr += t("welcome.device_abnormal_count", { count: res.deviceNum });
    }
    alertTitle.value = alarmStr;
  });
};

watch(() => locale.value, initAlarmDev);

const initOnOffDevFn = () => {
  const { group_idlist } = getSearchData();
  initOffDev({ group_idlist }).then(res => {
    offOnList.value[1].allNum = res.allNum;
    offOnList.value[1].num = res.onNum;
    offOnList.value[2].allNum = res.allNum;
    offOnList.value[2].num = res.offNum;
  });
};

const toNotice = () => {
  router.push("/notice/storeNotice");
};

async function getPointSync(
  BMap: any,
  address: string,
  city: string
): Promise<PointProp> {
  return new Promise((resolve, reject) => {
    const geocoder = new BMap.Geocoder();
    geocoder.getPoint(
      address,
      point => {
        if (point) {
          resolve(point);
        } else {
          reject(new Error(t("welcome.address_not_found")));
        }
      },
      city
    );
  });
}

const setPointMarker = (BMap: any) => {
  if (!BMap) return;
  const { group_idlist } = getSearchData();
  getStoreList({
    size: 0,
    group_idlist
  }).then(async res => {
    if (!res.data?.length) return;
    const pointData = new Map();
    for (const item of res.data) {
      try {
        const point = await getPointSync(
          BMap,
          item.province + item.city,
          item.city
        );

        const pointKey = point.lng + "_" + point.lat;
        if (pointData.has(pointKey)) {
          pointData.get(pointKey).push(item);
        } else {
          pointData.set(pointKey, [item]);
        }
      } catch (e) {}
    }

    bMapState.pointList = Array.from(pointData.entries());
    console.log("bMapState.pointList", pointData, bMapState.pointList);
  });
};

const initMap = ({ BMap, map }) => {
  console.log("initMap", BMap, map);
  bMapState.map = map;
  bMapState.bMap = BMap;
  map.enableScrollWheelZoom(true);
  map.setZoom(5.5);
  setPointMarker(BMap);
};

const overlayClick = (lng: string, lat: string) => {
  // const point = new bMapState.bMap.Point(lng, lat);
  // bMapState.map.setCenter(point);
  // bMapState.map.setZoom(9);
};

const submit = () => {
  // initTodayMake();
  initOnOffDevFn();
  // initPieChart();
  initCityBarChart();
  setPointMarker(bMapState.bMap);
};

onMounted(() => {
  submit();
  initAlarmDev();
});
</script>

<style scoped lang="scss">
.home-wrap {
  padding: 0 !important;

  /* 传统浏览器兼容 */
  @supports not (backdrop-filter: blur(10px)) {
    :deep(.vxe-card) {
      position: relative;
      overflow: hidden;

      &::before {
        position: absolute;
        inset: -20px;
        z-index: -1;
        content: "";
        background: inherit;
        filter: blur(10px);
        background-attachment: fixed;
      }
    }
  }

  :deep(.vxe-card) {
    //background-color: #ffffff70;
    background: rgb(255 255 255 / 60%);
    backdrop-filter: blur(2px);

    .vxe-card--body {
      height: 100%;

      .vxe-card--body-content {
        height: 100%;
      }
    }
  }

  .num-text {
    margin-top: 12px;
    font-family: DINAlternateBold, sans-serif;
    font-size: 30px;
    font-style: normal;
    font-weight: bold;
    line-height: 30px;
    color: var(--autata-font-color);
    text-align: left;
    letter-spacing: 1px;
  }

  .num-all {
    font-size: 20px;
    color: var(--autata-font-gray-color);
  }

  .bm-view {
    width: 100%;
    height: 100%;

    :deep(.anchorBL) {
      display: none;
    }
  }
}
</style>
